// 1. React核心库
import React, { useState, useRef } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, message, Space, Tag, Tooltip } from 'antd';

// 3. 图标库
import {
  ReloadOutlined,
  KeyOutlined,
  EyeOutlined
} from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ProColumns, ActionType } from '@ant-design/pro-components';

// 6. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 7. 生成的类型定义 (必须使用，禁止手工定义)
import type { PermissionList } from '@/services/generated/src/index';

const PermissionsListPage: React.FC = () => {
  const actionRef = useRef<ActionType>();

  // 查看权限详情
  const handleViewDetail = (permission: PermissionList) => {
    // 可以在这里添加查看详情的逻辑，比如打开Modal或跳转到详情页
    message.info(`查看权限详情: ${permission.name}`);
  };

  // 表格列定义 - 适配Django内建权限系统
  const columns: ProColumns<PermissionList>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: '权限代码名',
      dataIndex: 'codename',
      width: 200,
      copyable: true,
      ellipsis: true,
    },
    {
      title: '权限名称',
      dataIndex: 'name',
      width: 200,
      ellipsis: true,
    },
    {
      title: '显示名称',
      dataIndex: ['profile', 'display_name'],
      width: 150,
      search: false,
      render: (_, record) => record.profile?.display_name || '-',
    },
    {
      title: '应用标签',
      dataIndex: 'app_label',
      width: 120,
      valueType: 'select',
      valueEnum: {
        auth: { text: '认证' },
        permissions: { text: '权限管理' },
        contenttypes: { text: '内容类型' },
        sessions: { text: '会话' },
        admin: { text: '管理后台' },
      },
    },
    {
      title: '内容类型',
      dataIndex: 'content_type_name',
      width: 120,
      search: false,
    },
    {
      title: '权限分类',
      dataIndex: 'category_name',
      width: 120,
      search: false,
      render: (_, record) => record.profile?.category?.display_name || '-',
    },
    {
      title: '描述',
      dataIndex: ['profile', 'description'],
      width: 200,
      search: false,
      ellipsis: true,
      render: (_, record) => record.profile?.description || '-',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 100,
      render: (_, record) => [
        <Tooltip key="view" title="查看详情">
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          />
        </Tooltip>,
      ],
    },
  ];

  return (
    <PageContainer
      header={{
        title: '权限列表',
        subTitle: '管理系统权限定义',
      }}
    >
      <ProTable<PermissionList>
        columns={columns}
        actionRef={actionRef}
        request={async (params) => {
          try {
            await autoLoginInDev();

            const response = await apiClients.permissions.permissionsPermissionsList({
              page: params.current || 1,
              pageSize: params.pageSize || 20,
              search: params.name || params.codename,
              contentType: params.content_type,
              codename: params.codename,
            });

            console.log('🚀 Django内建权限列表API响应:', response);

            // 🔑 关键：手动提取data字段
            const responseData = (response as any).data || response;

            // 检查响应数据结构
            if (responseData && responseData.items) {
              return {
                data: responseData.items,
                success: true,
                total: responseData.total || 0,
              };
            } else {
              // 如果没有分页结构，直接使用响应数据
              return {
                data: Array.isArray(responseData) ? responseData : [],
                success: true,
                total: Array.isArray(responseData) ? responseData.length : 0,
              };
            }
          } catch (error) {
            console.error('权限列表API错误:', error);
            message.error('获取权限列表失败');
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
        }}
        dateFormatter="string"
        headerTitle="Django内建权限列表"
        toolBarRender={() => [
          <Button
            key="refresh"
            icon={<ReloadOutlined />}
            onClick={() => actionRef.current?.reload()}
          >
            刷新
          </Button>,
        ]}
      />
    </PageContainer>
  );
};

export default PermissionsListPage;